
import 'package:flutter/material.dart';

class LayoutSwitcher extends StatefulWidget {
  const LayoutSwitcher({super.key});

  @override
  State<LayoutSwitcher> createState() => _LayoutSwitcherState();
}

class _LayoutSwitcherState extends State<LayoutSwitcher> {
  bool showFirstLayout = true; // 控制显示哪个布局

  void _toggleLayout(bool showFirst) {
    setState(() {
      showFirstLayout = showFirst;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('布局切换示例')),
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: AnimatedSwitcher(
                duration: const Duration(milliseconds: 300), // 添加动画效果
                child: showFirstLayout ? const LayoutOne() : const LayoutTwo(),
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(
                onPressed: () => _toggleLayout(true),
                child: const Text('显示布局一'),
              ),
              ElevatedButton(
                onPressed: () => _toggleLayout(false),
                child: const Text('显示布局二'),
              ),
            ],
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }
}

class LayoutOne extends StatelessWidget {
  const LayoutOne({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      key: const ValueKey(1), // AnimatedSwitcher 需要唯一 Key
      color: Colors.blueAccent,
      width: 200,
      height: 200,
      alignment: Alignment.center,
      child: const Text(
        '布局一',
        style: TextStyle(color: Colors.white, fontSize: 24),
      ),
    );
  }
}

class LayoutTwo extends StatelessWidget {
  const LayoutTwo({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      key: const ValueKey(2),
      color: Colors.greenAccent,
      width: 200,
      height: 200,
      alignment: Alignment.center,
      child: const Text(
        '布局二',
        style: TextStyle(color: Colors.white, fontSize: 24),
      ),
    );
  }
}